import datetime

from django.http import HttpResponse, JsonResponse, HttpResponseRedirect
from django.shortcuts import render, redirect
# Create your views here.
from django.template.loader import render_to_string
from django.urls import reverse
from django.views.generic import TemplateView


def hello_world(request):
    return HttpResponse('hello world')

def hello_china(request):
    raise   #500错误
    print(reverse('hello_world'))   #URL的逆向解析
    return HttpResponse('hello china')


def hello_html(request):
    """响应HTML内容"""
    username = '张三'
    html = """
    <html>
        <body>
            <h1 style="color:#f00">hello {{html}}</h1>
        </body>
    </html>
    """.replace('{{html}}', username)      #模板：通过{{}}给替换掉
    return HttpResponse(html)


def article_list(request, month):
    """ request:request对象；month：今年某一个月的文章列表"""
    return HttpResponse('article:{}'.format(month))


def render_str(request):
    """render_to_string函数的使用"""
    templ_name = 'hello/index.html'
    html = render_to_string(template_name = templ_name)
    return HttpResponse(html)

def render_html(request):
    """render()函数的使用"""
    return render(request,'index.html')

def http_request(request):
    """请求练习"""
    # 1.请求方式
    print(request.method)
    # 2.请求头信息
    headers= request.META
    print(headers)
    ua = request.META.get('HTTP_USER_AGENT', None)
    print(ua)
    print(request.headers)
    print(request.headers['User-Agent'])
    print(request.headers['user-Agent'])
    # 3.获取请求参数
    name = request.GET.get('name', '')
    print(name)
    return HttpResponse('响应')


def http_response(request):
    """响应练习"""
    #resp = HttpResponse('响应内容', status=201)
    #resp.status_code=204
    #print(resp.status_code)
    #return resp
    user_info = {
        'name':'张三',
        'age':34,
    }
    return JsonResponse(user_info,json_dumps_params={'ensure_ascii':False}
)#加入json_dumps_params={'ensure_ascii':False}可解决中文乱码问题


def no_data_404(request):
    """404页面"""
    return HttpResponse('404')


def article_detail(request, article_id):
    """
    文章详情，ID从1000开始的整数
    article_id:文章ID
    """
    if article_id<1000:
       # return HttpResponseRedirect('/hello/404/')
        return redirect('no_data_404')#传一个视图函数的名称
    return HttpResponse('文章{}的内容'.format(article_id))


def search(request):
    """GET参数的获取"""
    name = request.GET.get('name', '')
    print(name)
    return HttpResponse('查询成功')

def index(request):
    return render(request, 'index.html')#响应HTML内容


class HomeView(TemplateView):
    template_name = 'home.html'

class Cat(object):

    def display(self):
        return '我是中华田园猫'

def index(request):
    username = '张三'
    age = 25
    img_url = '/media/images/dog.jpg'           #渲染静态图片

    list_users = [
        {'name':'张三','age':34},
        {'name':'李四','age':23},            #渲染python中的对象
    ]
    cat =Cat()
    return render(request,'index.html',{
        'username': username,
        'age': age,
        'img_url': img_url,
        'list_users': list_users,
        'cat':cat
    })                                        #渲染python中的变量

def tag(request):
    """DTL的标签练习"""
    list_users = [
        {'name': '张三', 'age': 34},
        {'name': '李四', 'age': 23, 'sex': '男'},
        {'name': '张三2', 'age': 34},
        {'name': '李四2', 'age': 23},
    ]
    # list_users =[]
    return render(request,'tag.html', {
        'list_users':list_users
    })

def test_filter(request):
    """过滤器的使用"""
    name = 'model'
    # list_user=[]
    list_user=False
    user_info=None
    pi = 3.1415926
    my_date = datetime.datetime(2050, 9, 28)
    html = '<h3>欢迎学习我们的python课程，祝大家学习愉快</h3>'
    return render(request,'test_filter.html',{
        'name': name,
        'list_user':list_user,
        'user_info':user_info,
        'pi':pi,
        'my_date': my_date,
        'html':html
    })

def mine_filter(request):
    """自定义过滤器"""
    uname='张三'
    return render(request,'mine_filter.html',{
        'uname':uname
    })